package com.zj.musicTools.function

import android.util.Log
import android.widget.Toast
import com.zj.musicTools.MainActivity
import com.zj.musicTools.function.AppPath.Companion.appPath
import org.json.JSONObject
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * 概述：APP总调度类，在主函数生成，全局调用。集成多个通用API，方便调用
 *
 *
 * */
object AgentStation {
    val executorService: ExecutorService = Executors.newFixedThreadPool(4) //线程数

//    companion object{
        init {
//            System.loadLibrary("um")
//            System.loadLibrary("ffmpeg")
            System.loadLibrary("handle");//CMakeList.txt 里面使用带jni接口的C文件编译出来的库名



        }
//        val Agent=AgentStation()

        @JvmStatic
        fun onProgressCallback(
            position: Int,
            duration: Int,
            @FFmpegState state: Int
        ) {
            /*Log.e(
                TAG, "onProgress position=" + position
                        + "--duration=" + duration + "--state=" + state
            )*/
            if (duration in 1 until position) {
                return
            }
            /*if (com.frank.ffmpeg.FFmpegCmd.mProgressListener != null) {
                if (position > 0 && duration > 0) {
                    val progress = position * 100 / duration
                    if (progress < 100) {
                        com.frank.ffmpeg.FFmpegCmd.mProgressListener.onProgress(progress, duration)
                    }
                } else {
                    com.frank.ffmpeg.FFmpegCmd.mProgressListener.onProgress(position, duration)
                }
            }*/
        }
        @JvmStatic
        fun onMsgCallback(msg: String?,level:Int) {

            if (!msg.isNullOrEmpty()) {
                if(level == 6) {
                    Log.e("ffmpeg()", "$msg")
                    FFMPEG.get().logCache(msg,true)
                } else {
                    Log.i("ffmpeg()", "$msg")
                    FFMPEG.get().logCache(msg)
                }

                //newLog(msg)
                // 静音检测回调
                /*if (msg.startsWith("silence") && com.frank.ffmpeg.FFmpegCmd.mProgressListener != null) {
                    com.frank.ffmpeg.FFmpegCmd.mProgressListener.onMsg(msg)
                }*/
            }
        }
//    }
    annotation class FFmpegState



     external fun decryptMusic(file: String,outfile: String): String
     external fun ffmpeg(command: Array<String>):Int

     external fun FcancelTask(TaskID:Int)


     /**
     *  针对decryptMusic()输出格式定制的log解析函数
     * */
    fun log(data:String):Boolean{
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // HH:mm:ss//获取当前时间
        val date = Date(System.currentTimeMillis())
        val formatted = simpleDateFormat.format(date)

        val filer= File(appPath.logPath())
        if(!filer.exists()) {
            filer.createNewFile()
            filer.appendText("["+formatted+"] LogPath:"+appPath.logPath()+"\n")
        }
        var result=data.get("result")
        val logdata=data.get("data")
        var dataPut:String=""
        if(result != null) {
            val split = logdata.toString().split("\n")
            if (result as Boolean) {
                val split1 = split[0].split("：")
                var details = ""
                for (i in 1 until split1.size) details += if (i > 1) "：" + split1[i] else split1[i]
                val split2 = details.split(";")
                dataPut = split1[0] + ":\n"
                for (i in 0 until split2.size)
                    dataPut += split2[i] + "\n"

            } else {
                try {
                    val split1 = split[1].split("：")
                    var details = ""
                    for (i in 1 until split1.size) details += if (i > 1) "：" + split1[i] else split1[i]
                    val split2 = details.split(";")
                    dataPut = split1[0] + ":\n"
                    for (i in 0 until split2.size)
                        dataPut += split2[i] + "\n"

                } catch (e: Exception) {
                    dataPut = logdata.toString() + "[" + appPath.input() + "]"
                }


            }

            filer.appendText("[" + formatted + "] result=" + result + ", data:" + dataPut)
            filer.appendText("\n")
        }else{
            result=true
            filer.appendText("[" + formatted + "] " + data)
            filer.appendText("\n")
        }

        return result
    }
    /**
     *  标准log输出函数
     * */
    fun log(result:Boolean,data:String):Boolean{
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // HH:mm:ss//获取当前时间
        val date = Date(System.currentTimeMillis())
        val formatted = simpleDateFormat.format(date)

        val filer= File(appPath.logPath())
        if(!filer.exists()) {
            filer.createNewFile()
            filer.appendText("["+formatted+"] LogPath:"+appPath.logPath()+"\n")
        }


        filer.appendText("[" + formatted + "] result=" + result + ", data:" + data)
        filer.appendText("\n")

        return result;
    }
    /**
     *  不判断log类型的单一log输出函数
     * */
    fun newLog(data:String){//后面可以增加一个bool变量用于判断正常log和错误log，改变字体颜色输出
        val simpleDateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss") // HH:mm:ss//获取当前时间
        val date = Date(System.currentTimeMillis())
        val formatted = simpleDateFormat.format(date)

        val filer= File(appPath.logPath())
        if(!filer.exists()){
            filer.createNewFile()
            filer.appendText("["+formatted+"] LogPath:"+appPath.logPath()+"\n")
        }

        filer.appendText("["+formatted+"] data:"+data+"\n")
    }
    fun ToastLog(text: String):String{
        Toast.makeText(MainActivity.CONTEXT, text, Toast.LENGTH_SHORT).show()
        return ""
    }

    // Json解析
    private operator fun String.get(key: String): Any? {
        return try {
            val jsonMessage = this
            val jsonObject = JSONObject(jsonMessage)
            jsonObject.get(key)
        } catch (e: Exception) {
            null
        }
    }



}